package com.imooc.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * cookie util
 * @author liuhuan
 * @date 2018/7/22 11:30
 * @description
 */
public class CookieUtil {
    public static void set(HttpServletResponse httpServletResponse,String name ,String value,int expire){
        Cookie cookie=new Cookie(name,value);
        cookie.setMaxAge(expire);
        httpServletResponse.addCookie(cookie);
    }

    /**
     * 从request中获取cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie get(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap=getCookieMap(request);
        if(cookieMap.containsKey(name)){
            return cookieMap.get(name);
        }else{
            return null;
        }
    }

    /**
     * 将cookie数组转为cookiemap
     * @param request
     * @return
     */
    private static  Map<String,Cookie> getCookieMap(HttpServletRequest request){
        Map<String,Cookie> cookieMap=new HashMap<>();
        Cookie [] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                cookieMap.put(cookie.getName(),cookie);
            }
        }
        return cookieMap;

    }
}
